import { Component, Host, ChangeDetectionStrategy, ChangeDetectorRef } from "@angular/core";
import { AppComponent } from "../../app.component";
import { FilterModel, FilterType, FilterStatus, ExportType } from "./models/filter.model";
import { ReportingService, TargetType } from "./reporting.service";
import { Router, ActivatedRoute } from "@angular/router";
import { LrtmService, LongRunningTaskTypeEnum } from "../../framework/lrtm/lrtm.service";
import { UtilsService } from "../../shared/services/utils.service";
import { StorageService } from "../../shared/services/storage.service";
import { AnalyticsService } from "../../shared/services/googleAnalytics.service";
import { GoogleAnalyticsBeacon } from "../../shared/models/googleAnalytics.model";

@Component({
    templateUrl: 'reporting.component.html',
    styleUrls: ['./reporting.component.scss'],
    providers: [ReportingService],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class ReportingComponent {
    public filters: FilterModel[];
    public filterType: typeof FilterType = FilterType;
    public targetType: typeof TargetType = TargetType;
    public type: TargetType;

    constructor(
        private cdRef: ChangeDetectorRef,
        private router: Router,
        private route: ActivatedRoute,
        @Host() private rootComponent: AppComponent,
        private toolsService: ReportingService,
        private lrtmService: LrtmService,
        private analyticsService: AnalyticsService
    ) { }

    ngOnInit() {
        this.route.params.subscribe(params => {
            this.type = params['type'];

            this.analyticsService.sendBeacon(new GoogleAnalyticsBeacon(this.type == TargetType.Screening ? 'ScreeningToolLandingPage' : 'ReportingToolLandingPage',
                this.type == TargetType.Screening ? 'Screening Tool' : 'Reporting Tool', {}));

            this.toolsService.getFilters(this.type).subscribe(data => {
                this.filters = data;
                this.cdRef.markForCheck();
                this.rootComponent.finishLoading();
            });
        });
    }

    public favouriteFilter(filter: FilterModel) {
        filter.isFavorite = !filter.isFavorite;
        this.cdRef.markForCheck();
        this.toolsService.updateFilter(filter, false).subscribe(data => { });
    }

    public createFilter(screening: boolean) {
        let count = this.filters.length;

        const type = screening ? 'filter' : 'report';
        var newName = 'new ' + type + ' (' + count + ')';
        while (this.filters.findIndex(x => x.name == newName) > -1) {
            var newName = 'new ' + type + ' (' + count++ + ')';
        }

        let model = new FilterModel();
        model.name = newName;
        model.exportType = ExportType.Excel;
        model.isFavorite = false;
        model.shared = false;
        model.status = FilterStatus.Active;
        model.targetType = screening ? TargetType.Screening : TargetType.Report;
        model.type = FilterType.Private;

        this.toolsService.updateFilter(model, false).subscribe(data => {
            this.router.navigate(['filter', data.id], { relativeTo: this.route });
        });

    }

    public shareFilter(filter: FilterModel) {
        this.toolsService.shareFilter(filter);
        this.cdRef.markForCheck();
    }

    public cloneFilter(filter: FilterModel) {
        //assign copy
        let clone: FilterModel = Object.assign({}, filter);

        clone.name = this.getCloneName(filter.name, 1);
        clone.isFavorite = false;
        clone.type = FilterType.Private;
        clone.shared = false;
        clone.status = FilterStatus.Active;
        clone.isSourceForClone = true;
        clone.targetType = this.type;
        this.toolsService.updateFilter(clone, false).subscribe(data => {
            let index: number = this.filters.findIndex(x => x.id == filter.id);
            if (index > -1) {
                data.isCurrentUserOwner = data.ownerUserId == StorageService.get().userInfo.userId;
                this.filters.splice(index + 1, 0, data);
                this.cdRef.detectChanges();
            }
        });
    }

    public removeFilter(filter: FilterModel) {
        this.toolsService.deleteFilter(filter.id).subscribe(data => {
            let index: number = this.filters.findIndex(x => x.id == filter.id);
            if (index > -1) {
                this.filters.splice(index, 1);
                this.cdRef.markForCheck();
            }
            this.toolsService.filterRemovedNotification(this.rootComponent);
        });
    }

    public generateFilter(filter: FilterModel) {
        //reset export type to Excel
        filter.exportType = ExportType.Excel;
        this.toolsService.updateFilter(filter, true).subscribe(_ => {
            this.lrtmService.runTask(this.rootComponent, `${filter.name}_${UtilsService.getReportDate()}`,
                filter.exportType == ExportType.CSV ? LongRunningTaskTypeEnum.ScreeningToolCSV : LongRunningTaskTypeEnum.ScreeningToolExcel, filter.id, true)
                .subscribe(data => { });
        })
    }

    private getCloneName(name: string, counter: number) {
        var cloneName = name + " (" + counter.toString() + ")";
        var found = this.filters.filter(item => { return item.name === cloneName; });

        if (found.length > 0) {
            counter += 1;
            return this.getCloneName(name, counter);
        }
        else {
            return cloneName;
        }
    }
}